//上传文件
export function upFile(file, url, success, error) {
  var formdata = new FormData();
  formdata.append("file", file);
  var xhr = new XMLHttpRequest();
  xhr.open("post", url);
  xhr.setRequestHeader("AUTHORIZATION", localStorage.getItem("TOKEN"));
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      success && success(JSON.parse(xhr.responseText));
    }
  };
  xhr.onerror = function () {
    error && error();
  };
  xhr.send(formdata);
}

//把毫秒 变成秒
export function timestamp(value) {
  return value / 1000;
}

// 转换Base64
export function convertImageToBase64(file, callback) {
  // 创建一个FileReader对象，它允许Web应用程序异步读取存储在计算机上的文件
  // 也就是file对象
  let reader = new FileReader();
  // 添加一个load事件，load会在加载完毕之后进行触发（也就是readAsDataURL读取完毕后触发）
  reader.addEventListener("load", function (e) {
    const base64Image = e.target.result; // 相当于reader.result 获取文件的Base64
    // 回收内存
    callback && callback(base64Image); // 调用callback压缩
    reader = null;
  });

  // readAsDataURL方法读取指定的file或blob对象
  reader.readAsDataURL(file);
}
/**
 * 将base64转换为文件
 * @param {baseURL} dataurl
 * @param {文件名称} filename
 * @return {文件二进制流}
 */
export function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

// 压缩算法函数
/* 
1.首先拿到了base64的图片字符串 
2.创建一个image对象
4.调用canvasAPI进行绘制新的图片
5.绘制成功之后调用canvasAPI进行绘制（canvasAPI支持压缩-二次压缩-从质量压缩）
6.得到压缩后的文件流
 */
export function compress(base64Image, fileName, callback) {
  let image = new Image();
  image.src = base64Image;

  image.addEventListener("load", function () {
    console.log("---->>>触发");
    // 获得长宽比例
    //创建一个canvas
    let canvas = document.createElement("canvas");
    //获取上下文
    let context = canvas.getContext("2d");

    canvas.width = 1024;

    canvas.height = 1024;
    // 防止重新上传覆盖
    context.clearRect(0, 0, canvas.width, canvas.height);
    //把图片绘制到canvas上面
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    // visibility hidden 需要创建的canvas隐藏 而不是不渲染DOM
    canvas.style.visibility = "hidden";
    //压缩图片，获取到新的base64Url
    const compressImage = canvas.toDataURL("image/jpeg", 0.8); // 通常压缩是0.8-0.9
    let resultFile = dataURLtoFile(compressImage, fileName);
    console.log("resultFile", resultFile);
    callback && callback(resultFile);
    // 接下来移除canvas元素 调用DOM.remove()
    canvas.remove();
  });
}

// 复制文本

export function copyText(text) {
  const textString = text.toString();
  let input = document.getElementById("#copy-input");
  if (!input) {
    input = document.createElement("input");
    input.id = "copy-input";
    input.readOnly = "readOnly"; // 防止ios聚焦触发键盘事件
    input.style.position = "absolute";
    input.style.left = "-1000px";
    input.style.zIndex = "-1000";
    document.body.appendChild(input);
  }
  input.value = textString;
  // ios必须先选中文字且不支持 input.select();
  try {
    input.select();
  } catch (error) {
    selectText(input, 0, textString.length);
  }

  document.execCommand("copy");
  input.blur();
  document.body.removeChild(input);

  function selectText(textbox, startIndex, stopIndex) {
    textbox.setSelectionRange(startIndex, stopIndex);
    textbox.focus();
  }
}

// 获取电话号码获取验证码次数
export function phoneGetCodeNum(type, phone) {
  let phoneGetCodeNK = JSON.parse(localStorage.getItem("phoneGetCodeNK"));
  let obj = phoneGetCodeNK[type];
  let num = obj[phone] || 0;
  return num;
}

// 设置电话号码获取验证码次数
export function phoneSetCodeNum(type, phone) {
  let phoneGetCodeNK = JSON.parse(localStorage.getItem("phoneGetCodeNK"));
  let obj = phoneGetCodeNK[type];

  if (phone in obj) {
    obj[phone] = Number(obj[phone]) + 1;
  } else {
    obj[phone] = 1;
  }
  localStorage.setItem("phoneGetCodeNK", JSON.stringify(phoneGetCodeNK));
}

// 传入时间戳，判断是否是当天
export function isNowDate(time) {
  var date = new Date(time);
  var year = date.getFullYear();
  var month = date.getMonth();
  var day = date.getDate();

  var dateN = new Date();
  var yearN = dateN.getFullYear();
  var monthN = dateN.getMonth();
  var dayN = dateN.getDate();

  if (day == dayN && month == monthN && yearN == year) {
    return true;
  } else {
    return false;
  }
}

// 时间戳转时间
export function getTime(time) {
  let t = "yyyy-MM-dd hh:mm";
  if (time) {
    let date = new Date(time * 1000);
    let month =
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1;
    let currentDate =
      date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    let hh = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    let mm =
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    t =
      date.getFullYear() +
      "-" +
      month +
      "-" +
      currentDate +
      " " +
      hh +
      ":" +
      mm;
  }
  return t;
}

export function getTimes(time) {
  let t = "yyyy-MM-dd hh:mm:ss";
  if (time) {
    let date = new Date(time * 1000);
    let month =
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1;
    let currentDate =
      date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    let hh = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    let mm =
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    let ss =
      date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    t =
      date.getFullYear() +
      "-" +
      month +
      "-" +
      currentDate +
      " " +
      hh +
      ":" +
      mm +
      ":" +
      ss;
  }
  return t;
}

// 设置，取消全屏
export function setAllScreen(flag, document) {
  var element = document.documentElement;
  if (flag) {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen();
    }
  } else {
    //取消全屏
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
      document.webkitCancelFullScreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
}

/*
 * formatMoney(s,type)
 * 功能：金额按千位逗号分割
 * 参数：s，需要格式化的金额数值.
 * 参数：type,判断格式化后的金额是否需要小数位.
 * 返回：返回格式化后的数值字符串.
 */
export function formatMoney(s, type) {
  // eslint-disable-next-line no-useless-escape
  if (/[^0-9\.]/.test(s)) return "0";
  if (s == null || s == "") return "0";
  s = s.toString().replace(/^(\d*)$/, "$1");
  s = (s + "").replace(/(\d*\.\d\d)\d*/, "$1");
  s = s.replace(".", ".");
  // s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
  // s = s.replace(".", ",");
  var re = /(\d)(\d{3},)/;
  while (re.test(s)) s = s.replace(re, "$1,$2");
  s = s.replace(/,(\d\d)$/, ".$1");
  if (type == 0) {
    // 不带小数位(默认是有小数位)
    var a = s.split(".");
    if (a[1] == "00") {
      s = a[0];
    }
  }
  return s;
}

export function removeEmptyValues(obj) {
  Object.keys(obj).forEach((key) => {
    if (obj[key] === null || obj[key] === undefined || obj[key] === "") {
      delete obj[key];
    }
  });
  return obj;
}
